package com.xyz.app.shiro;

import com.xyz.domain.table.CCustomer;
import com.xyz.service.CustomerService;
import com.xyz.shiro.BasicAuthorizingRealm;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.cache.ehcache.EhCacheCacheManager;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;

public class JwtRealm extends BasicAuthorizingRealm {

    CustomerService customerService;
    EhCacheCacheManager ehCacheCacheManager;

    public JwtRealm(CustomerService customerService, EhCacheCacheManager ehCacheCacheManager){
        this.customerService = customerService;
        this.ehCacheCacheManager = ehCacheCacheManager;
    }

    @Override
    public Function<PrincipalCollection, AuthorizationInfo> getAuthorizationFunc() {
        return null;
    }

    @Override
    public Function<AuthenticationToken, AuthenticationInfo> getAuthenticationFunc() {
        return token->{
            JwtToken jwtToken = (JwtToken) token;
            String tokenStr = jwtToken.getPrincipal().toString();
            CCustomer customer = customerService.getCustomerByToken(tokenStr);
            if(customer == null)
                throw new AuthenticationException("token过期，请重新登录");
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(customer, customer, "jwtRealm");
            return authenticationInfo;
        };
    }

    @Override
    public Function<AuthenticationToken, Boolean> getSupports() {
        return token -> token instanceof JwtToken;
    }
}
